package com.ctl.controller;

import com.ctl.config.MapBeanConfig;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;

//import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
public class ServerController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MapBeanConfig mapBeanConfig;
    @Autowired
    @Qualifier("serviceExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @RequestMapping("/send")
    @ResponseBody
    public Object send(HttpServletRequest request, String msg, String id, Long times) {
        if (times != null) {
            for (Long i = 0L; i < times; i++) {
                threadPoolTaskExecutor.submit(() -> {
                    Iterator<String> iterator = mapBeanConfig.getCtx().keySet().iterator();
                    while (iterator.hasNext()) {
                        try {
                            String idt = iterator.next();
                            Object obj = mapBeanConfig.getCtx().get(idt);
                            if (obj.getClass().getSimpleName().contains("ChannelHandlerContext")) {
                                ChannelHandlerContext chc = (ChannelHandlerContext) obj;
                                chc.write(idt + "#" + System.currentTimeMillis());
                                chc.flush();
                                redisTemplate.opsForValue().increment("msgtimes");
                            }
                        } catch (Exception e) {
                            log.error("", e);
                        }
                    }
                });
            }
        }
        return msg + System.currentTimeMillis();
    }

    @RequestMapping("/clients")
    @ResponseBody
    public Object clients(HttpServletRequest request) {
        Iterator<String> iterator = mapBeanConfig.getCtx().keySet().iterator();
        int i=0;
        while (iterator.hasNext()) {
            try {
                String idt = iterator.next();
                log.info("numbe={},id={}",++i, idt);
            } catch (Exception e) {
                log.error("", e);
            }
        }
        return mapBeanConfig.getCtx();
    }
}
